use ggez::GameResult;
use ggez::graphics::*;
use glam::*;

use crate::drawing::*;
use crate::view;

impl view::FloorExplorer {
    pub fn draw(&self, ctx: &DrawContext) -> GameResult {
        self.draw_floor_frame(ctx, |ctx| {
            draw_floor(&ctx, &self.logic_floor, &self.floor)
        })?;

        self.draw_outer(ctx)?;

        Ok(())
    }

    fn draw_floor_frame<F>(&self, ctx: &DrawContext, draw_inner: F) -> GameResult
    where
        F: Fn(DrawContext) -> GameResult,
    {
        let view::FloorExplorerLayout { floor_frame, .. } = self.layout;

        let translation = Mat4::from_translation(vec3(floor_frame.pos.x, floor_frame.pos.y, 0.0));

        let transform = ctx.transform * translation;

        draw_inner(DrawContext {
            transform,
            dim: floor_frame.dim,
            ..ctx.clone()
        })?;

        Ok(())
    }

    fn draw_outer(&self, ctx: &DrawContext) -> GameResult {
        let view::FloorExplorerLayout {
            dim, floor_frame, ..
        } = self.layout;

        let frame_mesh = MeshBuilder::new()
            .rectangle(
                DrawMode::Fill(FillOptions::default()),
                Rect::new(0.0, 0.0, dim.x, floor_frame.pos.y),
                Color::WHITE,
            )?
            .rectangle(
                DrawMode::Fill(FillOptions::default()),
                Rect::new(0.0, 0.0, floor_frame.pos.x, dim.y),
                Color::WHITE,
            )?
            .rectangle(
                DrawMode::Fill(FillOptions::default()),
                Rect::new(
                    floor_frame.pos.x + floor_frame.dim.x,
                    0.0,
                    dim.x - floor_frame.pos.x - floor_frame.dim.x,
                    dim.y,
                ),
                Color::WHITE,
            )?
            .rectangle(
                DrawMode::Fill(FillOptions::default()),
                Rect::new(
                    0.0,
                    floor_frame.pos.y + floor_frame.dim.y,
                    dim.x,
                    dim.y - floor_frame.pos.y - floor_frame.dim.y,
                ),
                Color::WHITE,
            )?
            .build(&mut ctx.ggez_ctx.borrow_mut())?;

        draw(
            &mut ctx.ggez_ctx.borrow_mut(),
            &frame_mesh,
            DrawParam::default().transform(ctx.transform),
        )?;

        Ok(())
    }
}
